import matplotlib.pylab as plt
import json
import java_interface


def get_points_indexes(points, indexes):
    result = []
    for i in indexes:
        result.append(points[i])
    return result


def get_data_from_file(file_name):
    with open('./data/' + file_name + '.json', 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
        return json_data


def get_plot_data(points):
    x = []
    y = []
    for p in points:
        x.append(p['x'])
        y.append(p['y'])
    x.append(x[0])
    y.append(y[0])
    return [x, y]


def get_xy_json(xy_list):
    r = []
    for i in xy_list:
        r.append({'x': i['x'], 'y': i['y']})
    return r


def plot(points, color='red', marker=None):
    if marker is None:
        plt.plot(*get_plot_data(points), color=color)
    else:
        plt.plot(*get_plot_data(points), color=color, marker=marker)


def get_turn_fit_extend(file_name):
    _gps_list = get_data_from_file(file_name)
    turn_fit_extend = java_interface.turn_fit_extend(_gps_list)['data']
    _turn = turn_fit_extend['turn']
    _fit = turn_fit_extend['fit']
    _extend = turn_fit_extend['extend']
    _turn_points = get_points_indexes(_gps_list, _turn)

    return _gps_list, _turn_points, get_xy_json(_fit), get_xy_json(_extend)


def draw_turn_fit_extend(gps_list, turn_points, fit, extend):
    plot(gps_list, color='red')
    plot(turn_points, color='blue', marker='.')
    plot(fit, color='green')
    plot(extend, color='yellow')
